package com.zxt.filter;

import com.zxt.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * JWT令牌验证过滤器
 * 拦截所有HTTP请求，对包含JWT令牌的请求进行合法性校验
 * 实现系统的统一身份认证和权限控制
 * 
 * @author liaowj
 * @version 1.0
 * @since 2025-07-01
 */

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;



        //1.获取url
        String requestURI = request.getRequestURI();

        //2.检验是不是login请求 是则放行
              if (requestURI.contains("login")){
                  filterChain.doFilter(request,response);
                  return;
              }

        //3.获取请求头中的token
        String token = request.getHeader("token");


        //4.检验token若不存在 则返回401 未登录
                 if (token == null||token.isEmpty()){
                     log.info("token为空");
                     response.setStatus(401);
                     return;
                 }

        //5.存在 检验是否正确 正确放行 错误401

        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token错误");
            response.setStatus(401);
            return;
        }

        //6.放行
        log.info("token正确");
        filterChain.doFilter(request,response);


    }
}
